package com.yenlien.traceyun.webase.dao;

import com.yenlien.traceyun.webase.config.ApplicationContextConfig;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-06-17
 * @description:
 **/
@Service
public class SqlQuery {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public <T> List<T> sqlQueryList(String sql, Class<T> clazz) {
//        Query query = ApplicationContextConfig.getEntityManager().createNativeQuery(sql,clazz);
//        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(clazz));
//        return query.getResultList();
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        NativeQuery query = session.createNativeQuery(sql);
//        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(clazz));
        query.unwrap(NativeQueryImpl.class).setResultTransformer(new SqlResultTransformer(clazz));
        return query.getResultList();
    }

    /**
     * sql原生查詢
     *
     * @param sql
     * @param
     * @return
     */

    @Transactional
    public List<Map<String, Object>> sqlQueryMap(String sql) {
        Query query = entityManager.createNativeQuery(sql);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();

    }

    /**
     * sql原生查詢
     *
     * @param sql
     * @param clazz
     * @param <T>
     * @return
     */

    @Transactional
    public <T> T sqlQueryOne(String sql, Class<T> clazz) {
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        NativeQuery query = session.createNativeQuery(sql);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(new SqlResultTransformer(clazz));
        return (T) query.getSingleResult();
    }
}
